package com.study.servlet.admin;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <pre>
 * -
 * Author : J.L.Zhou
 * E-Mail : 2233875735@qq.com
 * Tel : 151 1104 7708
 * Date : 2022-05-10 9:25
 * Version : 1.0
 * Copyright 2022 jlzhou.top Inc. All rights reserved.
 * Warning: this content is only for internal circulation of the company.
 *          It is forbidden to divulge it or use it for other commercial purposes.
 * </pre>
 **/
@WebServlet("/admin/upload.let")
@MultipartConfig(maxFileSize = -1, maxRequestSize = -1)
public class UploadServlet extends HttpServlet {

  /**
   * - 文件存放的目录
   */
  public final static File root = new File("e:/java/");
  private final static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("/yyyy/MM/dd/");

  @Override
  public void init() throws ServletException {
    System.out.println(this.getServletContext().getRealPath("/"));//获取站点应用的根目录
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String fileDesc = req.getParameter("fileDesc");//获取普通的表单参数值
    Part img = req.getPart("img");
    System.out.format("%s=%s\n","fileDesc",fileDesc);
    System.out.format("%s=%s\n","img.getName()",img.getName());
    System.out.format("%s=%s\n","img.getSubmittedFileName()",img.getSubmittedFileName());
    System.out.format("%s=%s\n","img.getContentType()",img.getContentType());
    System.out.format("%s=%s\n","img.getSize()",img.getSize());
    System.out.format("%s=%s\n","img.getInputStream()",img.getInputStream());


    //文件的保存
    //业务上可能需要将文件的信息存放到数据库中
    String uri = LocalDate.now().format(formatter);//获取存放的目录
    new File(root,uri).mkdirs();//创建要存放的目录
    uri+= UUID.randomUUID().toString().replace("-","").substring(5)+img.getSubmittedFileName().substring(img.getSubmittedFileName().lastIndexOf('.'));
    System.out.println(uri);
    img.write(new File(root,uri).getAbsolutePath());

    Map<String,Object> map = new HashMap<>();
    map.put("fileDesc", "fileDesc");
    map.put("name",img.getName());
    map.put("submittedFileName",img.getSubmittedFileName());
    map.put("contentType",img.getContentType());
    map.put("size",img.getSize());
    map.put("uri",uri);

    resp.setContentType("application/json;charset=utf-8");
    resp.getWriter().print(JSON.toJSONString(map));
    resp.flushBuffer();
  }
}
